package ru.arriah.common.web.action;

import java.util.*;
import java.beans.*;
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ActionUtils {
   protected ActionUtils() {
      super();
   }

   public static Object restoreBean(
      String beanClassName, ServletRequest request, Locale locale
   ) throws Exception {
      Class beanClass = Class.forName(beanClassName);
      Object bean = beanClass.newInstance();
      BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
      PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();

      for (PropertyDescriptor property: properties) {
         try {
            String propertyName = property.getName();

            String propertyValue =
               request.getParameter("_" + propertyName);

            Method setter = property.getWriteMethod();
            Class propertyClass = property.getPropertyType();
            String propertyClassName = propertyClass.getName();

            if (propertyClassName.equals(String.class.getName())) {
               setter.invoke(bean, propertyValue);
            } else {
               String setterName = setter.getName() + "FromString";

               setter =
                  beanClass.getMethod(
                     setterName, String.class, Locale.class
                  );

               setter.invoke(bean, propertyValue, locale);
            }
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

      return bean;
   }

   public static void setProperty(
      Object bean, String name, Object value, Class clazz
   ) {
      try {
         Class beanClass = bean.getClass();

         String setterName =
            "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

         Method setter = beanClass.getMethod(setterName, clazz);
         setter.invoke(bean, value);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
